
const fsm = wx.getFileSystemManager();
const requestUtil = require('request.js');
const app = getApp();
const basepath = `${wx.env.USER_DATA_PATH}`
 
//网络图片转base64转本地
function base64src(onlineSrc, cb) {
  var FILE_BASE_NAME = 'tmp_base64src_' + Math.ceil(Math.random() * 10000); //自定义文件名
  requestUtil.httpRequest({
    url: app.globalData.hostName + 'api/Url2Base64',
    method: 'GET',
    data: {
      imgUrl: onlineSrc,
    },
    success: (res) => {
      if (res.data.ResultCode == '0') {
        var base64data = res.data.ResultData;
        if (base64data) {
          base64data = JSON.stringify(base64data)
          const [, format, bodyData] = /data:image\/(\w+);base64,(.*)/.exec(base64data) || [];
          if (!format) {
            return (new Error('ERROR_BASE64SRC_PARSE'));
          }
          const filePath = `${wx.env.USER_DATA_PATH}/${FILE_BASE_NAME}.${format}`;
          const buffer = wx.base64ToArrayBuffer(bodyData);
          fsm.writeFile({
            filePath,
            data: buffer,
            encoding: 'binary',
            success() {
              cb(filePath);
            },
            fail(res) {
              console.log(res)
              wx.hideLoading();
              wx.showToast({
                title: '正在清理缓存，请稍后...',
                icon: 'none',
              })
              //清理缓存
              fsm.readdir({
 
                dirPath: basepath, /// 获取文件列表
 
                success(res) {
 
                  console.log(res)
 
                  res.files.forEach((val) => { // 遍历文件列表里的数据
 
                    console.log(val)
 
                    fsm.unlink({
 
                      filePath: basepath + '/' + val
 
                    });
 
                  })
 
                },
                fail(err) {
 
                  console.log(err)
 
                },
                complete() {
                  setTimeout(() => {
                    wx.navigateBack({
                      delta: 1
                    })
                  }, 1500)
 
                  console.log('complete')
 
                }
 
              })
              return (new Error('ERROR_BASE64SRC_WRITE'));
            },
          });
        }
      }
    }
  });
 
};
 
export {
  base64src
}